<template>
  <main class="login">
      <h1>Please login to continue</h1>
      <SmartForm class="form" :title="title" :operation="operation" :valid="valid">
        <FormInput name="username" placeholder="Username" v-model="username" />
        <FormInput name="password" type="password" placeholder="Password" v-model="password" />

      <template v-if="mode==='signup'">
        <FormInput name="verify-password" type="password" placeholder="Retype Password" v-model="password2" :invalid="retypePasswordError" />
        <FormInput name="email" placeholder="E-mail" v-model="email" type="email" />
      </template> 

      <template slot="actions">
        <template v-if="mode==='login'">
          <button type='button' class="secondary" @click="mode='signup'">Sign up</button>
          <button type="submit" :disabled="!valid">Login</button>
        </template> 

        <template v-else-if="mode==='signup'">
          <button type="button" class="secondary" @click="mode='login'">Back to login</button>
          <button type="submit" :disabled="!valid">Create account</button>
        </template>  
      </template> 
     </SmartForm>   
  </main>
</template>

<script>
import SmartForm from './SmartForm.vue'
import FormInput from './FormInput.vue'
export default {
  components: { SmartForm,FormInput },
  data(){
      return{
        mode:'login',
        username:'',
        password:'',
        password2:'',
        email:'',
      }
  },
  computed:{
    title(){
      if(this.mode==="login"){return "Login"}
      else if(this.mode==="signup"){return "Create a new account"}
      else return "Create a new account" 
    },
    retypePasswordError(){
      return this.password2 && this.password !==this.password2
    },
    signupValid(){
      return this.password2 && this.email && !this.retypePasswordError
    },
    valid(){
      return this.username && this.password && (this.mode !=="signup" || this.signupValid)
    }
  },
  methods:{
    async operation(){
      await this[this.mode]()
    },
    async login(){
      this.$state.user=await this.$fetch('login',{
        method:'POST',
        body:JSON.stringify({
          username:this.username,
          password:this.password
        }),
      })
      this.$router.replace(this.$route.params.wantedRoute||{name:'home'})

    },
    async signup(){
      await this.$fetch('signup',{
        method:"POST",
        body:JSON.stringify({
          username:this.username,
          password:this.password,
          email:this.email
        }),
      })
      this.mode="login"
    },
  },
}
</script>

<style lang="stylus" scoped>

</style>